package com.jie.netty.im;

import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 本地存储全部channel对应信息
 */
public class UserChannelCtxMap {

    /**
     *  主要维护im和通知的userId和ctx的关联关系，格式:Map<userId,map<terminal，ctx>>
     */
    private static Map<String, Map<Integer, ChannelHandlerContext>> channelMap = new ConcurrentHashMap();
    /**
     * 存储多人轨迹pk的组(房间号)id：组channel信息
     */
    private static Map<String, List<ChannelHandlerContext>> groupChannelMap = new ConcurrentHashMap<>();

    public static void addChannelCtx(String username, Integer channel, ChannelHandlerContext ctx) {
        channelMap.computeIfAbsent(username, key -> new ConcurrentHashMap()).put(channel, ctx);
    }

    public static void removeChannelCtx(String username, Integer terminal) {
        if (username != null && terminal != null && channelMap.containsKey(username)) {
            Map<Integer, ChannelHandlerContext> userChannelMap = channelMap.get(username);
            userChannelMap.remove(terminal);
        }
    }

    public static ChannelHandlerContext getChannelCtx(String username, Integer terminal) {
        if (username != null && terminal != null && channelMap.containsKey(username)) {
            Map<Integer, ChannelHandlerContext> userChannelMap = channelMap.get(username);
            if (userChannelMap.containsKey(terminal)) {
                return userChannelMap.get(terminal);
            }
        }
        return null;
    }

    public static Map<Integer, ChannelHandlerContext> getChannelCtx(String username) {
        if (username == null) {
            return null;
        }
        return channelMap.get(username);
    }
    public static void addGroupChannelCtx(String groupId, ChannelHandlerContext ctx) {
        groupChannelMap.computeIfAbsent(groupId, key -> new ArrayList<>()).add(ctx);
    }

    public static void removeGroupChannelCtx(Long groupId, ChannelHandlerContext ctx) {
        if (groupId!= null && groupChannelMap.containsKey(groupId)) {
            List<ChannelHandlerContext> ctxList = groupChannelMap.get(groupId);
            ctxList.remove(ctx);
        }
    }
    public static List<ChannelHandlerContext> getGroupChannelCtx(String groupId) {
        if (groupId== null && !groupChannelMap.containsKey(groupId)){
            return null;
        }
        return groupChannelMap.get(groupId);
    }
}
